package com.shishuo.cms.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.shishuo.cms.constant.ExceptionConstant;
import com.shishuo.cms.dao.UserWebEmailDao;
import com.shishuo.cms.entity.UserEntity;
import com.shishuo.cms.entity.UserWebEmail;
import com.shishuo.cms.entity.vo.PageVo;
import com.shishuo.cms.vo.ArticleEntityVo;
@Service
public class UserWebEmailService  extends BaseService<UserWebEmail, Long> {
	private UserWebEmailDao userWebEmailDao;
	@Autowired
	public void setUserWebEmailDao(UserWebEmailDao userWebEmailDao) {
		setBaseDao(userWebEmailDao);
		this.userWebEmailDao=userWebEmailDao;
	}
	@Autowired
	private UserService userService;
	
	@Transactional(rollbackFor=java.lang.Exception.class) 
	public void sendEmail(UserWebEmail userWebEmail, int isSendToAllUser) throws Exception {
		if (userWebEmail.getSendUserId()==0) {
			userWebEmail.setSendUserName("系统管理员");
		}
		if (isSendToAllUser==1) {
			List<UserEntity> userList=userService.getAllList();
			for (int i = 0; i < userList.size(); i++) {
				userWebEmail.setAcceptUserId(userList.get(i).getId());
				userWebEmail.setAcceptUserName(userList.get(i).getUserName());
				insert(userWebEmail);
			}
		}else {
			UserEntity userEntity=userService.getSingleUser(userWebEmail.getAcceptUserName());
			if (null==userEntity) {
				throw new Exception(ExceptionConstant.SEND_EMAIL_ERROR_USER_IS_NOT_EXIST);
			}else {
				userWebEmail.setAcceptUserId(userEntity.getId());
				userWebEmail.setAcceptUserName(userEntity.getUserName());
				insert(userWebEmail);
			}
		}
	}
	
	/**
	 * 跟进邮件接收人获取到分页邮件列表
	 * @param pageNum
	 * @param l
	 * @return
	 * @throws Exception
	 */
	public PageVo<UserWebEmail> getAllListPage(int pageNum,long acceptUserId) throws Exception{
		PageVo<UserWebEmail> pageVo = new PageVo<UserWebEmail>(pageNum);
		List<UserWebEmail> list =userWebEmailDao.getAllListVo(pageVo.getOffset(), pageVo.getRows(),acceptUserId);
		pageVo.setList(list);
		pageVo.setCount(userWebEmailDao.getAllListVoCount(acceptUserId));
		return pageVo;
	}

	public void readEmail(UserWebEmail userWebEmail) {
		userWebEmail.setIsRead(1);
		userWebEmailDao.update(userWebEmail);
	}
	
}
